import os
import cv2
from paddleocr import PPStructure,draw_structure_result,save_structure_res
from paddleocr.ppstructure.recovery.recovery_to_doc import sorted_layout_boxes, convert_info_docx
from PIL import Image
from fastapi.encoders import jsonable_encoder
import json 
import numpy as np
class ocr:
    ppstructure = PPStructure(show_log=False, recovery=True, lang='en', layout=True, structure_version= 'PP-StructureV2')
    
    def ___init___(self):
        super()
        self.ppstructure = PPStructure(show_log=False, recovery=True, lang='en', layout=True, structure_version= 'PP-StructureV2')
    # 获取ocr结构纠正后的结果
    def getRes(self, bytes):
        img = cv2.imdecode(np.frombuffer(bytes, dtype=np.uint8),1)
        #img = cv2.imencode('.png', img)
        #img = cv2.imread('./1.png')
        result = self.ppstructure(img)
        
        h, w, _ = img.shape # 记录图片的形状
        res = sorted_layout_boxes(result,w)
        for item in res:
            del item['img']
        print(res)
        
        return jsonable_encoder({
            'imgShape': {
                'h': h,
                'w': w
            },
            'res': res
        }) 